﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace TemplateGenerator.Controls {
	/// <summary>
	/// Interaction logic for EnterValuesControl.xaml
	/// </summary>
	public partial class EnterValuesControl : Window {

		public delegate void ImportHandler(object sender, Dictionary<string, string> values);
		public event ImportHandler OnImport;

		public Dictionary<string, string> fieldsNValues { get; set; }

		public EnterValuesControl() {
			InitializeComponent();
			fieldsNValues = new Dictionary<string, string>();

            //get username from active Word instance and place it in username textbox
			txtAuthor.Text = GeneratorHandler.WordApp.UserName;
		}

		private void BtnClose(object sender, RoutedEventArgs e) {
			Close();
		}

		private void btnImport_Click(object sender, RoutedEventArgs e) {
            //list of all the textbox controls which need to be checked for values
			List<Control> parseControl = new List<Control> { txtAuthor, txtClass, txtSchool, txtSubtitle, txtTitle };

            //run each control through the returnvalue function
			parseControl.ForEach(ReturnValue);

            //fire OnImport event and close the window
			OnImport(this, fieldsNValues);
			Close();
		}

		private void ReturnValue(Control control) {
            //checks if control has name
			if (control.Name == null) return;

            //check if control is a textbox
			if (control.GetType() == typeof(TextBox)) {
				TextBox textBox = (TextBox)control;
				string value = textBox.Text;

                //check if the textbox has a valid text
				if (String.IsNullOrWhiteSpace(value)) return;
                //add text to fieldsNValues, use textboxname (without txt) as key
				fieldsNValues.Add(textBox.Name.Replace("txt", ""), value);
			}
		}
	}
}
